package jumpingnotes.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doWork(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doWork(req, resp);
	}

	private void doWork(HttpServletRequest req, HttpServletResponse resp)
	{
		// add cookie
		String sessionId = (String) req.getParameter("SESSION_ID");
		Cookie cookie = new Cookie("SESSION_ID", sessionId);
		cookie.setMaxAge(req.getSession().getMaxInactiveInterval());
		resp.addCookie(cookie);

		try
		{
			PrintWriter out = resp.getWriter();
			out.print(sessionId);
			out.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
